package org.jsola.hr.web;

import com.alibaba.excel.EasyExcel;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.CustomCellWriteHandler;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.ChannelGroupAddDTO;
import org.jsola.hr.dto.ChannelGroupUpdateDTO;
import org.jsola.hr.query.ChannelGroupQuery;
import org.jsola.hr.service.IChannelGroupService;
import org.jsola.hr.vo.ChannelGroupListVO;
import org.jsola.hr.vo.ChannelGroupVO;
import org.jsola.hr.vo.ChannelGroupsVO;
import org.jsola.hr.vo.HrUserVO;
import org.jsola.salary.common.BigDecimalKit;
import org.jsola.salary.common.SalaryExcelKit;
import org.jsola.salary.query.ChannelFeeSettlementQuery;
import org.jsola.salary.vo.ChannelFeeSettlementVO;
import org.jsola.salary.vo.excel.ChannelFeeSettlementExportVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.validation.Valid;


/**
 * 渠道分组表
 *
 * @author zhr
 */
@RestController("hrChannelGroupController")
@RequestMapping(HrConstants.API_PATH + "/v1/channelGroups")
public class ChannelGroupController implements IChannelGroupControllerAPI {

    @Autowired
    private IChannelGroupService channelGroupService;

    @Override
    @PostMapping("/channelFeeSettlementExport")
    public ResponseEntity<Resource> channelFeeSettlementExport(@Valid @RequestBody ChannelFeeSettlementQuery channelFeeSettlementQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导出权限校验

        // 要导出的数据
        List<ChannelFeeSettlementExportVO> channelFeeSettlementExportVOList = channelGroupService.channelFeeSettlementExport(channelFeeSettlementQuery, tokenUser);
        // 导出excel
        InputStream is = getExcelInputStream(channelFeeSettlementExportVOList);
        String excelFilePath = SalaryExcelKit.exportExcel("channelFeeSettlement", "渠道劳务费结算", ChannelFeeSettlementExportVO.class, channelFeeSettlementExportVOList);
        // 编码文件名，防止乱码
        String filenames = FileKit.getNameAndEncode(excelFilePath);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new InputStreamResource(is));
    }

    private InputStream getExcelInputStream(List<ChannelFeeSettlementExportVO> channelFeeSettlementExportVOList) {
        List<List<String>> headList = new ArrayList<>();
        List<List<String>> dataList = new ArrayList<>();
        String[] strings = {"渠道名称", "身份证号", "所属分组", "产生费用人数", "工时抽成合计", "一次性费用合计", "特殊费用合计", "总费用合计"};
        for (String string : strings) {
            List<String> headList1 = new ArrayList<>();
            headList1.add(string);
            headList.add(headList1);
        }
        for (ChannelFeeSettlementExportVO channelFeeSettlementExportVO : channelFeeSettlementExportVOList) {
            List<String> headList2 = new ArrayList<>();
            if(StringUtils.isEmpty(channelFeeSettlementExportVO.getChannelName())){
                headList2.add("");
            }else {
                headList2.add(channelFeeSettlementExportVO.getChannelName());
            }
            if(StringUtils.isEmpty(channelFeeSettlementExportVO.getIdCard())){
                headList2.add("");
            }else {
                headList2.add(channelFeeSettlementExportVO.getIdCard());
            }
            if(StringUtils.isEmpty(channelFeeSettlementExportVO.getChannelGroupName())){
                headList2.add("");
            }else {
                headList2.add(channelFeeSettlementExportVO.getChannelGroupName());
            }
            if(channelFeeSettlementExportVO.getFeePeopleNumber() == null){
                headList2.add("");
            }else {
                headList2.add(channelFeeSettlementExportVO.getFeePeopleNumber()+"");
            }
            if(channelFeeSettlementExportVO.getSumWorkTimeRake() == null){
                headList2.add("");
            }else {
                headList2.add(channelFeeSettlementExportVO.getSumWorkTimeRake().intValue()+"");
            }
            if(StringUtils.isEmpty(channelFeeSettlementExportVO.getSumOneTimeFee())){
                headList2.add("");
            }else {
                headList2.add(channelFeeSettlementExportVO.getSumOneTimeFee().intValue()+"");
            }
            if(StringUtils.isEmpty(channelFeeSettlementExportVO.getSumSpecialFee())){
                headList2.add("");
            }else {
                headList2.add(channelFeeSettlementExportVO.getSumSpecialFee().intValue()+"");
            }
            if(StringUtils.isEmpty(channelFeeSettlementExportVO.getSumTotalFee())){
                headList2.add("");
            }else {
                headList2.add(channelFeeSettlementExportVO.getSumTotalFee().intValue()+"");
            }
            dataList.add(headList2);
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream)
                .head(headList)
                .registerWriteHandler(new CustomCellWriteHandler())
                .sheet("渠道劳务费结算")
                .doWrite(dataList);
        return new ByteArrayInputStream(outputStream.toByteArray());
    }

    @Override
    @PostMapping("/getChannelFeeSettlement")
    public Result<Page<ChannelFeeSettlementVO>> getChannelFeeSettlement(@Valid @RequestBody ChannelFeeSettlementQuery channelFeeSettlementQuery) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                channelGroupService.getChannelFeeSettlement(channelFeeSettlementQuery, tokenUser)
        );
    }

    @Override
    @GetMapping("/getNotDistributionUser")
    public Result<Page<HrUserVO>> getNotDistributionUser(ChannelGroupQuery channelGroupQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增渠道分组表权限校验

        return Result.success(
                channelGroupService.getNotDistributionUser(channelGroupQuery, tokenUser)
        );
    }

    @Override
    @GetMapping("/getMyChannelGroup")
    public Result<ChannelGroupsVO> getMyChannelGroup(ChannelGroupQuery channelGroupQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增渠道分组表权限校验

        return Result.success(
                channelGroupService.getMyChannelGroup(channelGroupQuery, tokenUser)
        );
    }

    @Override
    @PostMapping
    public Result<ChannelGroupVO> save(@Valid @RequestBody ChannelGroupAddDTO channelGroupAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增渠道分组表权限校验

        return Result.success(
                channelGroupService.save(channelGroupAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody ChannelGroupUpdateDTO channelGroupUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改渠道分组表权限校验

        int count = channelGroupService.update(channelGroupUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }



    @Override
    @DeleteMapping(value = "/{channelGroupId}")
    public Result<Integer> delete(@PathVariable String channelGroupId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除渠道分组表权限校验

        int count = channelGroupService.deleteByIds(tokenUser, channelGroupId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] channelGroupIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除渠道分组表权限校验

        int count = channelGroupService.deleteByIds(tokenUser, channelGroupIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{channelGroupId}")
    public Result<ChannelGroupVO> findById(@PathVariable String channelGroupId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看渠道分组表权限校验

        return Result.success(
            channelGroupService.selectById(channelGroupId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<ChannelGroupListVO>> listAll(@Valid ChannelGroupQuery channelGroupQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看渠道分组表权限校验
        List<ChannelGroupListVO> select = channelGroupService.select(channelGroupQuery, tokenUser.getSiteId());
        //增加默认分组
        ChannelGroupListVO channelGroupListVO = new ChannelGroupListVO();
        channelGroupListVO.setName("默认分组");
        channelGroupListVO.setId(HrConstants.DEFAULT.toUpperCase());
        select.add(0,channelGroupListVO);
        return Result.success(
                select
        );
    }


    @Override
    @GetMapping
    public Result<Page<ChannelGroupListVO>> page(@Valid ChannelGroupQuery channelGroupQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
            channelGroupService.selectPage(channelGroupQuery, tokenUser.getSiteId())
        );
    }


}

